<?php

namespace StickyNotes\Controller;


use Zend\View\Model\ViewModel;

use Zend\Mvc\Controller\AbstractActionController;

class StickyNotesController extends AbstractActionController
{
	
	protected $_stickNotesTable;
	
	public function getStickyNotesTable()
	{
		if(!$this->_stickNotesTable)
		{
			$sm = $this->getServiceLocator();
			$this->_stickNotesTable = $sm->get('StickyNotes\Model\StickyNotesTable');
		}

		return $this->_stickNotesTable;
	}
	
	public function indexAction()
	{
		return new ViewModel(array('stickyNotes' => $this->getStickyNotesTable()->fetchAll(),
				));
		
	}
	
	public function addAction()
	{
		$request = $this->getRequest();
		$response = $this->getResponse();
		
		if($request->isPost())
		{
			$new_note = new \StickyNotes\Model\Entity\StickyNote();
			if(!$note_id = $this->getStickyNotesTable()->saveStickyNote($new_note))
			{
				$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
				
			}else 
			{
				$response->setContent(\Zend\Json\Json::encode(array('response' => true, 'new_note_id' => $note_id)));
			}
		}
		return $response;
	}
	
	public function removeAction()
	{
		$request = $this->getRequest();
		$response = $this->getResponse();
		
		if($request->isPost())
		{
			$post_data = $request->getPost();
			$note_id = $post_data['id'];
			if(!$this->getStickyNotesTable()->removeStickyNote($note_id))
			{
				$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
			}else {
				$response->setContent(\Zend\Json\Json::encode(array('response' => true)));
			}
		}
	}
	
	public function updateAction()
	{
		$request = $this->getRequest();
		$response = $this->getResponse();
		
		if($request->isPost())
		{
			$post_data = $request->getPost();
			$note_id = $post_data['id'];
			$note_content = $post_data['content'];
			$stickyNote = $this->getStickyNotesTable()->getStickyNote($note_id);
						
			if(!$this->getStickyNotesTable()->saveStickyNote($stickyNote)){
				
				//$response->setContent(\Zend\Json\Json::encode(array('response' => false)));
			}else
			{
				$response->setContent(\Zend\Json\Json::encode(array('response' => true)));
			}
		}
		$response->setContent(\Zend\Json\Json::encode(array('response' => $this->getStickyNotesTable()->saveStickyNote($stickyNote))));
		return $response;
		
	}
}